package com.dc.service;

import com.dc.config.CommonConfig;
import com.dc.constant.Constants;
import com.dc.constant.MessageConstant;
import com.dc.dao.http.ElectricIdNameLogDao;
import com.dc.entity.http.ElectricIdNameEntity;
import com.dc.entity.http.IdNameLogEntity;
import com.dc.exception.ServiceException;
import com.dc.service.dto.electronic.*;
import com.dc.utils.DateUtils;
import com.dc.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;


@Service
@Slf4j
public class HttpService2 {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    CommonConfig commonConfig;

    @Resource
    ElectricIdNameLogDao electricIdNameLogDao;

    // 定时器每天晚上更新
    public String token;

    /**
     * 本方法获取 token ok
     * @return
     */
    public String getToken() {

        String account = commonConfig.getUsername();
        String password = commonConfig.getPassword();

        HttpLoginRequestBody requestPublishMessageDto = new HttpLoginRequestBody(account, password);

        String url = "/api/account/login";
        HttpEntity<HttpLoginRequestBody> entity = new HttpEntity<>(requestPublishMessageDto);
        ResponseEntity<ResponseResult<LinkedHashMap<String, Object>>> mapResponseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, new ParameterizedTypeReference<ResponseResult<LinkedHashMap<String, Object>>>() {});

        ResponseResult<LinkedHashMap<String, Object>> body = mapResponseEntity.getBody();
        if(!body.getIsSuccess()) {
            throw new ServiceException(MessageConstant.ERR_TOKEN_FAIL);
        }
        String token = body.getContent().get("token").toString();
        return token;
    }

    /**
     * 获得电表Id  电表name ok
     * @return  eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3VzZXJkYXRhIjoie1wiVXNlcklkXCI6XCIxODlkNzdjYS02MDE4LWVjMTEtYWFhMC1hNjRkY2EyODNjNWFcIixcIkFjY291bnRcIjpcIjE1MzM4MjU3NTI5XCIsXCJDb21wYW55SWRcIjpcImUyMTMxMTM2LTU1MTAtZTcxMS04MGU4LWE1NTUyMWRhMTg1OVwiLFwiUm9sZUlkXCI6XCIyMWNmYmIxMi0xYzM2LWU3MTEtODBlYS1jOTc5ODYyYWU3Y2JcIixcIkFjY291bnRUeXBlXCI6MCxcIkRhdGFQcmVjaXNpb25cIjoyfSIsIm5iZiI6MTczMzIzNTgxOSwiZXhwIjoxNzM1OTE0MjE5LCJpYXQiOjE3MzMyMzU4MTksImlzcyI6InNlbGYiLCJhdWQiOiJhbGwifQ.23gdBHdoVsiTbY6_5XQVVGAdF1gzN32UOoXbPrhC8mk
     */
    public List<HttpGetIdNameReturnNewBody> getElectricIdNames() {

        String url = "/api/mdata/getdeviceinfo";

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setBearerAuth(token);

        HttpEntity entity = new HttpEntity(httpHeaders);
        ResponseEntity<ResponseResult<List<HttpGetIdNameReturnNewBody>>> mapResponseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, new ParameterizedTypeReference<ResponseResult<List<HttpGetIdNameReturnNewBody>>>() {
        });
        ResponseResult<List<HttpGetIdNameReturnNewBody>> body = mapResponseEntity.getBody();
        if(!body.getIsSuccess()) {
            throw new ServiceException(url + " : 调用失败...");
        }

        List<HttpGetIdNameReturnNewBody> content = body.getContent();

        return content;
    }

    // 调用方法 获取电量, 小时级别
    public Map<String, HttpGetPowerReturnNewBody> getPowerListByHourType(Set<String> mfids, Date startTime, Date endTime) {
        return getPowerList(mfids, Constants.DATE_TYPE_HOUR, startTime, endTime);
    }

    // 调用方法 获取电量
    public Map<String, HttpGetPowerReturnNewBody> getPowerList(Set<String> mfids, Integer dateType, Date startTime, Date endTime) {

//        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3VzZXJkYXRhIjoie1wiVXNlcklkXCI6XCIxODlkNzdjYS02MDE4LWVjMTEtYWFhMC1hNjRkY2EyODNjNWFcIixcIkFjY291bnRcIjpcIjE1MzM4MjU3NTI5XCIsXCJDb21wYW55SWRcIjpcImUyMTMxMTM2LTU1MTAtZTcxMS04MGU4LWE1NTUyMWRhMTg1OVwiLFwiUm9sZUlkXCI6XCIyMWNmYmIxMi0xYzM2LWU3MTEtODBlYS1jOTc5ODYyYWU3Y2JcIixcIkFjY291bnRUeXBlXCI6MCxcIkRhdGFQcmVjaXNpb25cIjoyfSIsIm5iZiI6MTczMzIzNTgxOSwiZXhwIjoxNzM1OTE0MjE5LCJpYXQiOjE3MzMyMzU4MTksImlzcyI6InNlbGYiLCJhdWQiOiJhbGwifQ.23gdBHdoVsiTbY6_5XQVVGAdF1gzN32UOoXbPrhC8mk";

        String url = "/api/mdata/getdevicedata?dateTye={dateType}&startTime={startTime}&endTime={endTime}";

        Map<String, HttpGetPowerReturnNewBody> result = new LinkedHashMap<>();

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setBearerAuth(token);

        List<String> body = new ArrayList<>(mfids);

        Map<String, Object> map = new HashMap<>();
        map.put("startTime", DateUtils.dateTime(startTime));
        map.put("endTime", DateUtils.dateTime(endTime));
        map.put("dateType", dateType);

        HttpEntity<List<String>> httpEntity = new HttpEntity<>(body, httpHeaders);
        ResponseEntity<ResponseResult<List<HttpGetPowerReturnNewBody>>> forEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, new ParameterizedTypeReference<ResponseResult<List<HttpGetPowerReturnNewBody>>>() {
        }, map);

        ResponseResult<List<HttpGetPowerReturnNewBody>> resBody = forEntity.getBody();
        if(!resBody.getIsSuccess()) {
            throw new ServiceException(url + " : 调用失败...");
        }
        List<HttpGetPowerReturnNewBody> content = resBody.getContent();
        content.forEach(t->{
            String midId = t.getMfId();
            result.put(midId, t);
        });
        return result;
    }

    // 日期时间-电量
    public List<DDataInfo> getPowerByDayTimeList(Map<String, HttpGetPowerReturnNewBody> map) {
        List<DDataInfo> result = new ArrayList<>();
        for (Map.Entry<String, HttpGetPowerReturnNewBody> entry : map.entrySet()) {
            HttpGetPowerReturnNewBody body = entry.getValue();
            System.out.println(body.getData());
            result = HttpGetPowerReturnNewBody.mergePower(result, body.getData());
        }
        return result;
    }

    public void insertLog(ElectricIdNameEntity before, ElectricIdNameEntity after) {
        try {
            String nameBefore = before.getName();
            String nameAfter = after.getName();
            if(!nameAfter.equals(nameBefore)) {
                String jsonBefore = JsonUtils.toJson(before);
                String jsonAfter = JsonUtils.toJson(after);
                IdNameLogEntity entity = new IdNameLogEntity(null, "修改", jsonBefore, jsonAfter, null);
                electricIdNameLogDao.save(entity);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

}
